import {Material2} from "./material2";
import {Color} from "../core/color";
import {VertexData} from "../core/vertexData";
import {Renderer2} from "../core/renderer2";
import {ShaderProgram} from "../core/shaderProgram";
import {bindVAO, createVAO, deleteVAO, deleteVBO, unbindVAO} from "../core/utils";

export class LambertMaterial extends Material2 {



    normalVBO:WebGLBuffer | null = null;

    static ProgramName = "LambertMaterial";
    constructor(
        vertexData:VertexData,
        color: Color = new Color(0xffffffff),
    ) {
        super(vertexData,color);
    }

    init(): void {
        let renderer = Renderer2.instance();
        let program = renderer.getProgame(LambertMaterial.ProgramName);
        let gl = renderer.gl;

        this.vao = createVAO(gl);
        bindVAO(gl,this.vao!);
        this.checkPosVBO(gl,program);
        this.checkNormalVBO(gl,program);
        this.checkIndiceVBO(gl);

        // wireframe
        let wireFrameProgram = renderer.getProgame(Material2.WireFrame);
        this.lineVAO = createVAO(gl);
        bindVAO(gl,this.lineVAO!);
        this.checkLinePosVBO(gl,wireFrameProgram);
        this.checkLineIndiceVBO(gl);

        // boundingbox
        this.bbVAO = createVAO(gl);
        bindVAO(gl,this.bbVAO!);
        this.checkBBPosVBO(gl,wireFrameProgram);
        this.checkBBIndiceVBO(gl);

        unbindVAO(gl);
    }

    cleanup(): void {
        let gl = Renderer2.instance().gl;
        deleteVAO(gl,this.vao);
        deleteVBO(gl,this.posVBO);
        deleteVBO(gl,this.normalVBO);
        deleteVBO(gl,this.indiceVBO);

        // wireframe
        deleteVAO(gl,this.lineVAO);
        deleteVBO(gl,this.linePosVBO);
        deleteVBO(gl,this.lineIndiceVBO);

        // bb
        deleteVAO(gl,this.bbVAO);
        deleteVBO(gl,this.bbPosVBO);
        deleteVBO(gl,this.bbIndicesVBO);
    }

    checkNormalVBO(gl:WebGLRenderingContext,program:ShaderProgram){
        if (!this.normalVBO){
            this.normalVBO = gl.createBuffer();
            gl.bindBuffer(gl.ARRAY_BUFFER,this.normalVBO);
            gl.bufferData(gl.ARRAY_BUFFER,this.vertexData.normalBufferData,gl.STATIC_DRAW);
            let attribLocation = program.getAttribId("a_normal");
            gl.enableVertexAttribArray(attribLocation);
            gl.vertexAttribPointer(attribLocation,3,gl.FLOAT,false,0,0);
        }
    }

}
